import java.io.*;
import java.net.Socket;

/**
 * @author: macy
 * @Email: 420534221@qq.com
 * @Date: 2020/8/15
 * @describe:
 */
public class MySocketClient {


    private Socket soc = null;
    private String server = "";
    private int port = 0;

    public MySocketClient(String server, int port) throws Exception{
        super();
        this.server = server;
        this.port = port;
        soc = new Socket(server, port);
    }

    //给服务器发送消息
    public void sendMsgToServer(String msg) throws IOException{
        OutputStream out = soc.getOutputStream();
        out.write(msg.getBytes());
    }

    //从服务器接收消息
    public void recMsgFromServer() {
        byte[] b = null;
        StringBuilder text = null;
        while (true) {
            try {
                InputStream in = soc.getInputStream();
                b = new byte[1024];
                int len = 0;
                while ((len = in.read(b)) != -1) {
                    String strText = new String(b, 0, len,"GB2312");
                    System.out.println(strText);
                    writeDataToTxt(strText);
                }
            } catch (IOException e) {
                System.out.println("读取数据出错:"+e.getMessage());
            }
        }
    }

    public void writeDataToTxt(String strText) {
        String fileName = "D:\\data\\temp\\sok_temp.txt";
        File f = new File(fileName);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(f, f.exists());
            strText = "\n" + strText;
            out.write(strText.getBytes());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                out.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

}
